/**
 * Copyright (C) 2017-2050 http://www.ejianmedia.com/ 冯兵兵 <cnrainbing@163.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.fastadmin.common.mapper;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.netty.util.concurrent.FastThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import static org.springframework.http.HttpStatus.OK;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

import static com.google.common.collect.ImmutableMap.of;

/**
 *
 * @Author: YangKun
 * @Date: 19-6-16
 */
public class JsonMapper {
	private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);

	private ObjectMapper mapper;

	public JsonMapper() {
		this(null);
	}

	
	public JsonMapper(Include include) {
		mapper = new ObjectMapper();
		// 设置输出时包含属性的风格
		if (include != null) {
			mapper.setSerializationInclusion(include);
		}
        mapper.registerModule(new Jdk8Module());
		mapper.registerModule(new JavaTimeModule());
		// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
		mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	/**
	 * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
	 */
	public static JsonMapper nonEmptyMapper() {
		return mFastThreadLocalNnEmptyMapper.get();
	}

	private static final FastThreadLocal<JsonMapper> mFastThreadLocalNnEmptyMapper = new FastThreadLocal<JsonMapper>() {
		@Override
		protected JsonMapper initialValue() {
			return new JsonMapper(Include.NON_EMPTY);
		}
	};

	/**
	 * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式，建议在内部接口中使用。
	 */
	public static JsonMapper nonDefaultMapper() {
		return mFastThreadLocalNonDefaultMapper.get();
	}

	private static final FastThreadLocal<JsonMapper> mFastThreadLocalNonDefaultMapper = new FastThreadLocal<JsonMapper>() {
		@Override
		protected JsonMapper initialValue() {
			return new JsonMapper(Include.NON_DEFAULT);
		}
	};
	
	/**
	 * Object可以是POJO，也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
	 */
	public String toJson(Object object) {

		try {
			return mapper.writeValueAsString(object);
		} catch (IOException e) {
			logger.warn("write to json string error:" + object, e);
			return null;
		}
	}

	/**
	 * 反序列化POJO或简单Collection如List<String>.
	 * 
	 * 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
	 * 
	 * 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String, JavaType)
	 * 
	 * @see #fromJson(String, JavaType)
	 */
	public <T> T fromJson(String jsonString, Class<T> clazz) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}

		try {
			return mapper.readValue(jsonString, clazz);
		} catch (IOException e) {
			logger.warn("parse json string error:" + jsonString, e);
			return null;
		}
	}

	/**
	 * 反序列化复杂Collection如List<Bean>,
	 * 先使用createCollectionType()或contructMapType()构造类型, 然后调用本函数.
	 *
	 * @see # createCollectionType(Class, Class...)
	 */
	public <T> T fromJson(String jsonString, JavaType javaType) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}

		try {
			return mapper.readValue(jsonString, javaType);
		} catch (IOException e) {
			logger.warn("parse json string error:" + jsonString, e);
			return null;
		}
	}

    /**
     * Converts a JsonNode to a Java value
     *
     * @param <A> the type of the return value.
     * @param json Json value to convert.
     * @param clazz Expected Java value type.
     * @return the return value.
     */
    public <A> A fromJson(JsonNode json, Class<A> clazz) {
        try {
            return mapper.treeToValue(json, clazz);
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

	/**
	 * 构造Collection类型.
	 */
	public JavaType contructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
		return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
	}

	/**
	 * 构造Map类型.
	 */
	public JavaType contructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
		return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
	}

	/**
	 * 当JSON里只含有Bean的部分屬性時，更新一個已存在Bean，只覆蓋該部分的屬性.
	 */
	public void update(String jsonString, Object object) {
		try {
			mapper.readerForUpdating(object).readValue(jsonString);
		} catch (JsonProcessingException e) {
			logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
		} catch (IOException e) {
			logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
		}
	}

	/**
	 * 輸出JSONP格式數據.
	 */
	public String toJsonP(String functionName, Object object) {
		return toJson(new JSONPObject(functionName, object));
	}

	/**
	 * 設定是否使用Enum的toString函數來讀寫Enum, 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
	 * 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
	 */
	public void enableEnumUseToString() {
		mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
		mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
	}

	/**
	 * 取出Mapper做进一步的设置或使用其他序列化API.
	 */
	public ObjectMapper getMapper() {
		return mapper;
	}

    /**
     * Creates a new empty ObjectNode.
     * @return new empty ObjectNode.
     */
    public ObjectNode newObject() {
        return getMapper().createObjectNode();
    }

    /**
     * Creates a new empty ArrayNode.
     * @return a new empty ArrayNode.
     */
    public ArrayNode newArray() {
        return getMapper().createArrayNode();
    }

    /**
     * Parses a String representing a json, and return it as a JsonNode.
     * @param src    the JSON string.
     * @return the JSON node.
     */
    public JsonNode parse(String src) {
        try {
            return getMapper().readTree(src);
        } catch(Throwable t) {
            throw new RuntimeException(t);
        }
    }


	public String buildJson(int code, String msg) {
		return toJson(of("code", code, "msg", msg));
	}
	public String buildJson(int code, String msg, Object data) {
		return toJson(of("code", code, "msg", msg, "obj", data));
	}
	public String ok() {
		return toJson(of("code", OK.value(), "msg", OK.getReasonPhrase()));
	}

	public String ok(Object data) {
		if (Objects.isNull(data)) {
			return ok();
		}
		return toJson(of("code", OK.value(), "msg", OK.getReasonPhrase(), "obj", data));
	}

	public String error() {
		return toJson(of("code", HttpStatus.INTERNAL_SERVER_ERROR.value(), "msg", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()));
	}
	public String error(Object data) {
		if (Objects.isNull(data)) {
			return error();
		}
		return toJson(of("code", HttpStatus.INTERNAL_SERVER_ERROR.value(), "msg", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "obj", data));
	}



}
